package cn.bellychang.websocket;

import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

/**
 * @author ChangLiang
 * @date 2020/3/5
 */
public class ClientRunnable implements Runnable {

    public static final String EXIT = "exit";
    String uri = "ws://192.168.211.2:8080/chat-room/java-client";
    Session session;
    WebSocketContainer container = null;

    @Override
    public void run() {
        try {
            container = ContainerProvider.getWebSocketContainer();
        } catch (Exception ex) {
            System.out.println("error" + ex);
        }
        try {
            URI r = URI.create(uri);
            session = container.connectToServer(WebsocketClient.class, r);
        } catch (DeploymentException | IOException e) {
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        try {
            do {
                input = br.readLine();
                if (!input.equals(EXIT)) {
                    session.getBasicRemote().sendText(input);
                }
            } while (!input.equals(EXIT));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
